package org.chen.aao.file.controller;

import org.chen.aao.common.file.dto.FileUploadResponse;
import org.chen.aao.common.response.Result;
import org.chen.aao.file.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    
    private final FileService fileService;
    
    @PostMapping("/upload/audio")
    public Result<FileUploadResponse> uploadAudio(@RequestParam("file") MultipartFile file,
                                                  HttpServletRequest request) throws IOException {
        Long userId = getUserId(request);
        return Result.success(fileService.uploadAudio(file, userId));
    }
    
    @PostMapping("/upload/image")
    public Result<FileUploadResponse> uploadImage(@RequestParam("file") MultipartFile file,
                                                  HttpServletRequest request) throws IOException {
        Long userId = getUserId(request);
        return Result.success(fileService.uploadImage(file, userId));
    }
    
    @DeleteMapping("/delete")
    public Result<?> deleteFile(@RequestParam("url") String fileUrl,
                                HttpServletRequest request) {
        fileService.deleteFile(fileUrl);
        return Result.success("文件删除成功");
    }
    
    private Long getUserId(HttpServletRequest request) {
        return (Long) request.getAttribute("userId");
    }
}